/*
 * @FileName: [RechargecardController.java]
 * 
 * @Package controller
 * 
 * 
 * Copyright (c) 2011-2015 BCINFO Technology Limited Com. All rights reserved.
 * 
 * This software is the confidential and proprietary information of BCINFO Technology Limited Company ("Confidential Information"). You shall not disclose such Confidential Information and shall use it only in accordance with the terms of the contract agreement you entered into with RKY.
 * 
 * $Rev: 797 $ $LastChangedDate: 2013-12-25 15:06:51 +0800 (Wed, 25 Dec 2013) $ $LastChangedBy: xusp $
 * 
 * @category bcinfo-upp
 * 
 * @version 1.1
 * 
 * @author $Author: xusp $
 * 
 * Change History:[Formatter: author date description] <br/> 1 2 3
 */

package com.bcinfo.iccard.admin.iccard.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.bcinfo.iccard.admin.common.ModuleEnum;
import com.bcinfo.iccard.admin.controller.AbstractController;
import com.bcinfo.iccard.constant.ExportReportConstant;
import com.bcinfo.iccard.constant.MerchantConstant;
import com.bcinfo.iccard.exception.ExpensiveRecordsNotExistException;
import com.bcinfo.iccard.exception.IccardDatabaseException;
import com.bcinfo.iccard.exception.IccardException;
import com.bcinfo.iccard.exception.InvalidParametersException;
import com.bcinfo.iccard.exception.MerchantBillingExpenseRecordErrorException;
import com.bcinfo.iccard.exception.MerchantBillingFuncErrorException;
import com.bcinfo.iccard.exception.MerchantIsNotExistException;
import com.bcinfo.iccard.model.CardSaleTotal;
import com.bcinfo.iccard.model.Merchant;
import com.bcinfo.iccard.model.MerchantSettlementAmountDetail;
import com.bcinfo.iccard.model.SettlementExportReport;
import com.bcinfo.iccard.service.FinancialManageService;
import com.bcinfo.iccard.util.DownloadUtils;
import com.bcinfo.iccard.util.PaginationList;

/**
 * 财务管理controller <br/>
 * <p>
 * Description:<br/>
 * <p>
 * 包含以下功能 <br/>
 * <br/>
 * 
 * <PRE>
 *      /iccard/${actionName}
 * </PRE>
 * <p>
 */
@Controller
@RequestMapping("/iccard/financialmanage")
public class FinancialManageController extends AbstractController
{
    @Autowired()
    private FinancialManageService financialManageService;

    /*
     * (non-Javadoc) Description: <br/>
     * 
     * @return
     * 
     * @see com.bcinfo.upp.admin.controller.AdminController#getMouduleCode()
     */
    public String getMouduleCode()
    {
        return ModuleEnum.FinancialManage.moduleName.value;
    }

    @RequestMapping("/saleStatistics")
    @ResponseBody
    public Map<String, Object> saleStatistics(String beginTime, String endTime)
    {
        Map<String, Object> map = new HashMap<String, Object>();
        PaginationList<CardSaleTotal> list = null;

        try
        {
            list = financialManageService.saleStatistics(beginTime, endTime, getPage(), getPageSize());
            if (list != null)
            {
                map.put("rows", list.getRecords());
                map.put("total", list.getTotalRecord());
            }
        }
        catch (IccardException e)
        {
            map.put("total", 0);
            handleException(e);
        }
        catch (Exception e)
        {
            map.put("total", 0);
            handleException(e);
        }

        return map;
    }

    // 收益额统计 汇总
    @ResponseBody
    @RequestMapping("/totalSaleAmount")
    public Map<String, Object> incomeReportSum(String beginTime, String endTime)
    {

        Map<String, Object> map = new HashMap<String, Object>();
        float totalSaleAmount = financialManageService.selectTotalSaleAmount(beginTime, endTime);
        map.put("totalSaleAmount", totalSaleAmount);
        return map;
    }

    @ResponseBody
    @RequestMapping("/statusManage")
    public Map<String, Object> statusManage(String sellerCode)
    {
        String param = "";
        if (StringUtils.isNotBlank(sellerCode))
        {
            String[] ss = sellerCode.split(",");
            param = ss[0];
        }
        Map<String, Object> map = new HashMap<String, Object>();
        try
        {
            PaginationList<Merchant> plist = financialManageService.findByCodeAndStatus(param,
                    MerchantConstant.MERCHANT_CHECK_STATUS_1, MerchantConstant.MERCHANT_STATUS_1, getPage(),
                    getPageSize());
            if (plist != null)
            {
                map.put("rows", plist.getRecords());
                map.put("total", plist.getTotalRecord());
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return map;
    }

    @RequestMapping("/changeStatus")
    @ResponseBody
    public Map<String, String> changeStatus(Long merchantId, Integer status)
    {
        // if (!this.hasPermission(ModuleEnum.RechargeableCard.add))// 没有权限
        // {
        // _log.error("权限不足");
        // return packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, null, "权限不足");
        // }
        Map<String, String> map = null;
        try
        {
            financialManageService.updateStatus(merchantId, status);

            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS, ERROR_VALUE_MSG_TYPE_INFO,
                    ERROR_VALUE_OP_RESULT_SUCCESS_NAME, null);
            addLog(ModuleEnum.Merchant.changeStatus, "changeStatus=" + "merchantId=" + merchantId);
        }
        catch (IccardDatabaseException e)
        {
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, e.getClass()
                    .getSimpleName(), "数据库错误");
            addLog(ModuleEnum.Merchant.changeStatus, "数据库错误");
        }
        catch (MerchantBillingFuncErrorException e)
        {
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, e.getClass()
                    .getSimpleName(), "为避免影响报表生成，一天之内不能重复开启和关闭结算功能");
            addLog(ModuleEnum.Merchant.changeStatus, "为避免影响报表生成，一天之内不能重复开启和关闭结算功能");
        }
        catch (MerchantBillingExpenseRecordErrorException e)
        {
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, e.getClass()
                    .getSimpleName(), "请先导出未结算报表");
            addLog(ModuleEnum.Merchant.changeStatus, "请先导出未结算报表");
        }
        return map;
    }

    /**
     * 未导出<br/>
     * <p>
     * Description: TODO(详细描述) <br/>
     * <p>
     * Author: Administrator<br/>
     * <p>
     * Date: 2013-12-20-下午01:47:43<br/>
     * <p>
     * 
     * @param sellerCode
     * @return
     * 
     */
    @ResponseBody
    @RequestMapping("/reportNotExportList")
    public Map<String, Object> reportNotExportList()
    {
        Map<String, Object> map = new HashMap<String, Object>();
        try
        {
            PaginationList<SettlementExportReport> plist = financialManageService.findReportsExportByStatus(
                    ExportReportConstant.EXPORTREPORT_STATUS_0, "", "", getPage(), getPageSize());
            if (plist != null)
            {
                map.put("rows", plist.getRecords());
                map.put("total", plist.getTotalRecord());
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 已导出 <br/>
     * <p>
     * Description: TODO(详细描述) <br/>
     * <p>
     * Author: Administrator<br/>
     * <p>
     * Date: 2013-12-20-下午01:49:48<br/>
     * <p>
     * 
     * @param sellerCode
     * @return
     * 
     */
    @ResponseBody
    @RequestMapping("/reportAlreadyExportList")
    public Map<String, Object> reportAlreadyExportList(String beginTime, String endTime)
    {
        Map<String, Object> map = new HashMap<String, Object>();
        try
        {
            PaginationList<SettlementExportReport> plist = financialManageService.findReportsExportByStatus(
                    ExportReportConstant.EXPORTREPORT_STATUS_1, beginTime, endTime, getPage(), getPageSize());
            if (plist != null)
            {
                map.put("rows", plist.getRecords());
                map.put("total", plist.getTotalRecord());
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 商家未结算明细 <br/>
     * <p>
     * Description: TODO(详细描述) <br/>
     * <p>
     * Author: Administrator<br/>
     * <p>
     * Date: 2013-12-20-下午03:52:28<br/>
     * <p>
     * 
     * @param beginTime
     * @param endTime
     * @return
     * 
     */
    @ResponseBody
    @RequestMapping("/notSettleMerchantDetailList")
    public Map<String, Object> notSettleMerchantDetailList(Long settlementExportReportId, String merchantName,
            String beginTime, String endTime)
    {
        Map<String, Object> map = new HashMap<String, Object>();
        try
        {
            PaginationList<MerchantSettlementAmountDetail> plist = financialManageService.findNotSettleMerchantDetails(
                    settlementExportReportId, merchantName, beginTime, endTime, getPage(), getPageSize());
            if (plist != null)
            {
                map.put("rows", plist.getRecords());
                map.put("total", plist.getTotalRecord());
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return map;
    }

    @RequestMapping("/exportReport")
    @ResponseBody
    public Map<String, String> exportReport(Long settlementExportReportId)
    {
        // if (!this.hasPermission(ModuleEnum.RechargeableCard.add))// 没有权限
        // {
        // _log.error("权限不足");
        // return packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, null, "权限不足");
        // }
        Map<String, String> map = null;
        try
        {
            financialManageService.exportReport(settlementExportReportId);

            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS, ERROR_VALUE_MSG_TYPE_INFO,
                    ERROR_VALUE_OP_RESULT_SUCCESS_NAME, null);
            addLog(ModuleEnum.Merchant.exportReport, "settlementExportReportId=" + settlementExportReportId);
        }
        catch (IccardDatabaseException e)
        {
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, e.getClass()
                    .getSimpleName(), "数据库错误");
            addLog(ModuleEnum.Merchant.exportReport, "数据库错误");
        }
        catch (MerchantIsNotExistException e)
        {
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, e.getClass()
                    .getSimpleName(), "商家不存在");
            addLog(ModuleEnum.Merchant.exportReport, "商家不存在");
        }
        catch (ExpensiveRecordsNotExistException e)
        {
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, e.getClass()
                    .getSimpleName(), "商家对应的游客消费记录不存在");
            addLog(ModuleEnum.Merchant.exportReport, "商家对应的游客消费记录不存在");
        }
        return map;
    }

    @RequestMapping("/exportReportAll")
    @ResponseBody
    public Map<String, String> exportReportAll()
    {
        // if (!this.hasPermission(ModuleEnum.RechargeableCard.add))// 没有权限
        // {
        // _log.error("权限不足");
        // return packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, null, "权限不足");
        // }
        Map<String, String> map = null;
        try
        {
            financialManageService.exportReportAll();
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS, ERROR_VALUE_MSG_TYPE_INFO,
                    ERROR_VALUE_OP_RESULT_SUCCESS_NAME, null);
            addLog(ModuleEnum.Merchant.exportReportAll, "settlementExportReportIds=");
        }
        catch (IccardDatabaseException e)
        {
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, e.getClass()
                    .getSimpleName(), "数据库错误");
            addLog(ModuleEnum.Merchant.exportReportAll, "数据库错误");
        }
        catch (InvalidParametersException e)
        {
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, e.getClass()
                    .getSimpleName(), "参数异常");
            addLog(ModuleEnum.Merchant.exportReportAll, "参数异常");
        }
        catch (MerchantIsNotExistException e)
        {
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, e.getClass()
                    .getSimpleName(), "报表中有商家id不存在,请联系系统管理员");
            addLog(ModuleEnum.Merchant.exportReport, "报表中有商家id不存在,请联系系统管理员");
        }
        catch (ExpensiveRecordsNotExistException e)
        {
            map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR, e.getClass()
                    .getSimpleName(), "商家对应的游客消费记录不存在");
            addLog(ModuleEnum.Merchant.exportReport, "商家对应的游客消费记录不存在");
        }
        return map;
    }

    @RequestMapping("/download")
    public ModelAndView download(HttpServletResponse response) throws Exception
    {
        Long settlementExportReportId = null;
        String reportId = request.getParameter("settlementExportReportId");
        String path = request.getParameter("path");
        SettlementExportReport report = null;
        String realPath = request.getSession().getServletContext().getRealPath("/") + File.separator;
        String addr = "";
        // 一键下载，查询出所有的path
        if (StringUtils.isBlank(reportId))
        {
            try
            {
                
                PaginationList<SettlementExportReport> plist = financialManageService.findReportsExportByStatus(
                        ExportReportConstant.EXPORTREPORT_STATUS_0, "", "", 1, 100000);
                List<SettlementExportReport> list = plist.getRecords();
                List<String> pathList = new ArrayList<String>();
                for (SettlementExportReport settlementExportReport : list)
                {
                    addr = settlementExportReport.getExportReportAddr();
                    path = realPath + addr;
                    pathList.add(path);
                }
                String tempPath = realPath + "\\report\\temp";
//                tempPath = "F:\\BCinfo\\SVN\\汇卡充值卡结算清分系统-代码\\trunk\\iccard-root\\iccard-admin\\src\\main\\webapp\\iccard\\financialmanage\\download"
//                        + File.separator + DownloadConstant.TEMP_ZIP_NAME;
                DownloadUtils.downLoadFiles(pathList, tempPath, request, response);
            }
            catch (IccardDatabaseException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            catch (InvalidParametersException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            catch (MerchantIsNotExistException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            catch (ExpensiveRecordsNotExistException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        // 单个下载
        else
        {
            settlementExportReportId = Long.parseLong(reportId);
            try
            {
                report = financialManageService.findByReportId(settlementExportReportId);
                addr = report.getExportReportAddr();
            }
            catch (IccardDatabaseException e1)
            {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            path = realPath + addr;
            try
            {
                DownloadUtils.downLoadFile(path, request, response);
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
        return null;

    }


    private void writeJsonObject(HttpServletRequest request, HttpServletResponse resp, String jsonData)
    {
        resp.setContentType("text/html;charset=utf-8");
        resp.setCharacterEncoding("utf-8");
        PrintWriter pw = null;
        try
        {
            pw = resp.getWriter();
            pw.print(jsonData);
            pw.flush();
        }
        catch (IOException e)
        {
            handleException(e);
        }
        finally
        {
            if (null != pw)
            {
                pw.close();
            }
        }
    }
}